package com.example.goodtrash.search;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.goodtrash.R;
import com.example.goodtrash.model.Result;
import com.example.goodtrash.model.Trash;
import com.example.goodtrash.util.HttpUtil;
import com.example.goodtrash.util.Utility;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.gson.Gson;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class VoiceSearch extends AppCompatActivity {
    private ImageView ivPicture;
    private List<Trash> dataList=new ArrayList<>();
    private TrashAdapter adapter;
    private RecyclerView rvResult;
    private ProgressDialog progressDialog;
    private MaterialToolbar toolbar;
    private static final int REQUEST_CODE = 2;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.RECORD_AUDIO"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_search);
        toolbar=findViewById(R.id.toolbar);
        rvResult=findViewById(R.id.rv_result);
        adapter=new TrashAdapter(dataList,VoiceSearch.this,VoiceSearch.this);
        rvResult.setLayoutManager(new LinearLayoutManager(this));
        rvResult.setAdapter(adapter);
        SpeechUtility.createUtility(VoiceSearch.this, SpeechConstant.APPID +"=47331a22");

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            //未赋予权限，申请权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .RECORD_AUDIO)) {
                //选择不开启权限的时候，提示用户
                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_CODE);

        } else {
            //权限已赋予
            Toast.makeText(this, "已授权成功！", Toast.LENGTH_SHORT).show();
        }
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }



    public void voiceInput(View view){
        initSpeech(this);

    }



    public void initSpeech(final Context context) {
        //1.创建RecognizerDialog对象
        RecognizerDialog mDialog = new RecognizerDialog(context,null);
        //2.设置accent、language等参数
        mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mDialog.setParameter(SpeechConstant.ACCENT, "mandarin");

        //3.设置回调接口
        mDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult recognizerResult, boolean isLast) {
                if (!isLast) {
                    //解析语音
                    //返回的result为识别后的汉字
                    String result = parseVoice(recognizerResult.getResultString());
                    Toast.makeText(VoiceSearch.this,result,Toast.LENGTH_SHORT).show();
                    showLoadingDialog(result);
                    HttpUtil.sendOkHttpRequest(result, new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            Toast.makeText(VoiceSearch.this,"搜索失败",Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            String responseText=response.body().string();
                            Result result1= Utility.handleTrashResponse(responseText);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(result1!=null&&"success".equals(result1.getMessage())){

                                        closeProgressDialog();
                                        dataList.clear();
                                        List<Trash> trashList=result1.getTrashList();
                                        for(Trash trash: trashList) {
                                            dataList.add(trash);
                                        }
                                        adapter.notifyDataSetChanged();

                                    } else if("No match result".equals(result1.getMessage())){
                                        closeProgressDialog();
                                        Toast.makeText(VoiceSearch.this,"搜索到知识盲区啦",Toast.LENGTH_SHORT).show();
                                    } else if ("param error".equals(result1.getMessage())){
                                        closeProgressDialog();
                                        Toast.makeText(VoiceSearch.this,"请输入简体中文",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    });

                }
            }

            @Override
            public void onError(SpeechError speechError) {
                Toast.makeText(VoiceSearch.this,"识别失败",Toast.LENGTH_SHORT).show();
            }
        });
        //4.显示dialog，接收语音输入
        mDialog.show();
    }

    /**
     * 解析语音json
     */
    public String parseVoice(String resultString) {
        Gson gson = new Gson();
        Voice voiceBean = gson.fromJson(resultString, Voice.class);

        StringBuffer sb = new StringBuffer();
        ArrayList<Voice.WSBean> ws = voiceBean.ws;
        for (Voice.WSBean wsBean : ws) {
            String word = wsBean.cw.get(0).w;
            sb.append(word);
        }
        return sb.toString();
    }


    /**
     * 语音实体类
     */
    public class Voice {

        public ArrayList<WSBean> ws;

        public class WSBean {
            public ArrayList<CWBean> cw;
        }

        public class CWBean {
            public String w;
        }
    }


    private void showLoadingDialog(String result){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(VoiceSearch.this);
            progressDialog.setMessage("正在搜索"+result);
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }


    private void closeProgressDialog(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //权限的申请结果返回
            case REQUEST_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //已授权
                    Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show();
                } else {
                    //未授权
                    Toast.makeText(this, "授权被拒绝！", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }

    }
}


